import { useAMap } from '@/components/utils/useMap';
import { defineComponent, PropType, ref, watch } from 'vue';
import { QuestionType } from '../typing';

export default defineComponent({
  props: {
    question: {
      type: Object as PropType<QuestionType>,
      required: true,
    },
    language: {
      type: String as PropType<'zh' | 'en'>,
      required: true,
    },
    value: {
      type: Object as PropType<any>,
    },
  },
  emits: ['update:value'],
  setup(props, { emit }) {
    const { language, question } = props;
    const questionProper =
      language === 'zh' ? question.questionProperZh : question.questionProperEn;
    const mapContainerId = `map-container-${question.id}`;
    const mapMarker = ref();

    const AMapCallback = (context: any) => {
      const { AMap, Map, PlaceSearch } = context;
      if (questionProper!.mapItem?.searchKey) {
        PlaceSearch.search(questionProper!.mapItem?.searchKey);
      }

      Map.on('click', (e: any) => {
        if (question.mode !== 'design') {
          if (mapMarker.value) {
            Map.remove(mapMarker.value);
          }

          mapMarker.value = new AMap.Marker({
            position: e.lnglat,
          });

          mapMarker.value.setMap(Map);
          emit('update:value', e.lnglat);
        }
      });

      watch(
        () => questionProper!.mapItem?.searchKey,
        () => {
          PlaceSearch.search(questionProper!.mapItem?.searchKey);
        },
      );
    };

    useAMap(mapContainerId, AMapCallback);

    return () => {
      return (
        <div
          class={[
            'question-container',
            'question-map-container',
            { 'question-design': question.mode === 'design' },
          ]}
        >
          <div class="question-title" v-html={questionProper!.title}></div>
          <div id={mapContainerId} style="width: 100%;height: 250px"></div>
        </div>
      );
    };
  },
});
